<?php

namespace app\manage\services;

use app\common\loader\ModelSystem;
use app\common\loader\Services;
use think\Exception;

/**
 * 角色管理
 */
class SystemRoleService
{
    /**
     * 角色管理分页
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getPage(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,title,data_permission,description';
        }
        $list = ModelSystem::SystemRoles()->page($options);
        Services::Helper()->showListTitle($list['data'], [], ['data_permission' => 'system.data_permission']);
        return $list;
    }

    /**
     * 角色列表
     * @param array $option
     * @param bool $allField
     * @return mixed
     * @throws \think\Exception
     */
    public function getList(array $option, bool $allField = true)
    {
        if (!$allField) {
            $option['field'] = 'id,title';
        }
        return ModelSystem::SystemRoles()->setOption($option)->select();

    }


    /**
     * 删除角色
     */
    public function roleDel(int $id): int
    {
        if (ModelSystem::SystemManager()->where("role_id", $id)->count() > 0) {
            api_exception(API_ERROR, "该权限组下存在用户！不能删除");
        }
        $model = ModelSystem::SystemRoles();
        return $model->removeOption()->where("id", $id)->delete();
    }


    /**
     *  角色组信息
     * @param  $options
     * @return array
     * @throws Exception
     */
    public function roleInfo($options): array
    {
        return ModelSystem::SystemApi()->actions($options);
    }

    /**
     *  角色组编辑删除
     * @param array $params
     * @return int|string
     * @throws Exception
     */
    public function roleSave(array $params)
    {
        try {
            return ModelSystem::SystemRoles()->addEdit($params);
        } catch (Exception $e) {
            throw $e;
        }
    }

}
